package server;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author czq
 * @date 2020/7/30 23:36
 *
 * 自定义类加载器
 */
public class MyClassLoder extends ClassLoader {

    private static final Map<String, Class<?>> classMap = new HashMap<>();

    private String path;

    public MyClassLoder() {
    }

    public MyClassLoder(ClassLoader classLoader, String path) {
        super(classLoader);
        this.path = path;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        Class<?> result = classMap.get(path + name);
        if (result != null) {
            return result;
        }

        byte[] data = loadClassData(name);
        if (data == null) {
            return super.findClass(name);
        }

        result = defineClass(name, data, 0, data.length);
        classMap.put(path + name, result);

        return result;
    }

    /**
     * 读取并加载类文件获得byte数组返回
     * @param name
     * @return
     */
    private byte[] loadClassData(String name) {

        FileInputStream fileInputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        byte[] data = null;

        try {
            name = name.replaceAll("\\.", "/");
            fileInputStream = new FileInputStream(path + name + ".class");
            byteArrayOutputStream = new ByteArrayOutputStream();

            int ch = 0;
            while ((ch = fileInputStream.read()) != -1) {
                byteArrayOutputStream.write(ch);
            }
            data = byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                byteArrayOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return data;
    }
}
